﻿
namespace GameStudio.IDE.Controls
{
    using System.Windows;
    using System.Windows.Controls;
    using GameStudio.Common;
    using GameStudio.IDE.Common.Events;
    using Microsoft.Practices.ServiceLocation;
    using Utils.EventAggregator;
    using GameStudio.IDE.Common;
    using GraphicsDesigner.Controls;

    [TemplatePart(Name = "uxMDITab", Type = typeof(TabControl))]
    public class TabContainer : Control
    {
        private TabControl uxMDITab;

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            uxMDITab = (TabControl)GetTemplateChild("uxMDITab");
        }

        public TabContainer()
        {
            //initialize templates
            ProjectCreateInfo projectTemplate = new ProjectCreateInfo();
            System.IO.Directory.CreateDirectory(ProjectCreateInfo.TmpLocation);
            projectTemplate.CreateTemplate();

            var eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
            eventAggregator.GetEvent<CreateProjectEvent>().Subscribe(AddNewTab);
            eventAggregator.GetEvent<AddNewItemEvent>().Subscribe(OnAddNewItem);
            eventAggregator.GetEvent<OpenItemEvent>().Subscribe(OpenItem);
        }

        private void AddNewTab(GameStudio.IDE.Common.Project project)
        {
            TabItem item = new TabItem();
            item.Header = project.Name;
            this.uxMDITab.Items.Add(item);
        }

        private void OnAddNewItem(GameStudio.IDE.Common.Item item)
        {
            TabItem tabItem = new TabItem();

            if (item.Type == "Class")
            {
                ControlTemplate template = (ControlTemplate)FindResource("CodeEditorControlTemplate");
                tabItem.Content = new CodeEditorControl() { Template = template };
            }
            else if (item.Type == "Model")
            {
                ControlTemplate template = (ControlTemplate)FindResource("DesignerControlTemplate");
                //tabItem.Content = new DesignerControl(item.Name,item.Path) { Template = template }; --> Error
            }

            tabItem.Header = item.Name; ;
            tabItem.Focus();
            this.uxMDITab.Items.Add(tabItem);
        }

        private void OpenItem(string str)
        {
            TabItem tabItem = new TabItem();

            ControlTemplate template = (ControlTemplate)FindResource("CodeEditorControlTemplate");
            tabItem.Content = new CodeEditorControl() { Template = template };

            tabItem.Header = str;

            tabItem.Focus();
            this.uxMDITab.Items.Add(tabItem);

        }

    }
}
